package com.battle.pojo.converter;
import com.alibaba.fastjson.JSON;
import cn.hutool.json.JSONUtil;
import jakarta.persistence.AttributeConverter;
import java.lang.reflect.ParameterizedType;
import com.alibaba.fastjson.TypeReference;
import jakarta.persistence.Converter;

@Converter(autoApply = false)
public  class ListObjectConvert<M> implements AttributeConverter<M, String> {
    @Override
    public String convertToDatabaseColumn(M attribute) {
        return JSON.toJSONString(attribute);
    }

    @Override
    public M convertToEntityAttribute(String dbData) {
        if (isList()) {
            return JSON.parseObject(dbData, getTypeReference());
        }
        return JSON.parseObject(dbData, getTypeArguement());
    }

    private boolean isList() {
        return ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName().contains("java.util.List");
    }

    protected TypeReference<M> getTypeReference() {
        return new TypeReference<M>(){};
    }

    /**
     * 获取T的实际类型
     */
    public Class<M> getTypeArguement() {
        Class<M> tClass = (Class<M>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return tClass;
    }

}